# rm(list = ls());
gc()

# source("00_pckgs.R")

# set.seed(1917)

options(mc.cores = parallel::detectCores())

if (!file.exists("results/mc/res.txt")){
  file.create("results/mc/res.txt")
  js <- sample(1:1000, 100)
} else {
  done <- read.table("results/mc/res.txt") %>% 
    pull(V2)
  if (length(c(1:1000)[!(c(1:1000) %in% done)]) > 100){
    js <- sample(c(1:1000)[!(c(1:1000) %in% done)], 100) 
  } else {
    js <- c(1:1000)[!(c(1:1000) %in% done)]
  }
}
  
for (j in js){
  load(paste0("data/mc/", j, "_run.Rda"))
  
  stan_data <- list(
    D = 2,
    K = 1,
    Y = y_b,
    J = 100,
    I = 250,
    incl_nonsep = 0,
    incl_logl = 1,
    theta_true = id,
    theta_in = abind(cbind(id_i[,1]),
                     cbind(id_i[,2]), along = 3)
  )
  
  initF <- function() {
    list(
      theta_free = matrix(rep(0, 200), ncol = 2),
      bk_free = prop + matrix(rnorm(500, 0, .5), ncol = 2),
      ak = prop_diff + rnorm(250, 0, .5),
      sal_free = c(-.5, .5),
      L = chol(diag(c(1, 1), 2, 2)),
      gamma = matrix(c(1, 1), ncol = 1, nrow = 2)
    )
  }
  
  mod <- cmdstan_model("mod_mc.stan")
  
  fit <- mod$sample(data = stan_data, init = initF, iter_warmup = 500, iter_sampling = 500, seed = 2021)
  loo_sep <- fit$loo()
  sum_sep <- fit$summary(c("sal", "r_true", "r_dim", "r_sq", "gamma_post", "m_prop_compl", "sd_prop_compl", "p_share"))
  
  stan_data$incl_nonsep <- 1
  
  fit2 <- mod$sample(data = stan_data, init = initF, iter_warmup = 500, iter_sampling = 500, seed = 2021)
  loo_nonsep <- fit2$loo()
  sum_nonsep <- fit2$summary(c("sal", "r_true", "r_dim", "r_sq", "gamma_post", "m_prop_compl", "sd_prop_compl", "DL", "p_share"))
  
  loo_comp <- loo::loo_compare(loo_sep, loo_nonsep)
  save(sum_sep, sum_nonsep,
       loo_comp,
       file = paste0("results/mc/", j, "_run.Rda"))
  
  rm(dl, taus,
     prop, prop_diff, id, id_i,
     sum_sep, sum_nonsep, mod,
     loo_sep, loo_nonsep,
     fit, fit2)
  end <- Sys.time()
  write(paste0("session ", j, " ", end), file = "results/mc/res.txt", append = TRUE)
  
  gc();Sys.sleep(15);gc()
}

# rstudioapi::restartSession(command = "")
